package com.jia.lidao;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.jia.lidao.enity.Agent;
import com.jia.lidao.enity.AuthInfo;
import com.jia.lidao.ui.login.LoginActivity;
import com.jia.lidao.utils.SharedPrefConfig;

/**
 * Created by jia on 17/12/28.
 */

public class UserUtils {

    private static UserUtils instance;

    private Context context;

    private SharedPrefConfig config;


    private AuthInfo authInfo;

    private Agent agent;

    private Gson gson;

    public static UserUtils getInstance() {
        if (null == instance) {
            synchronized (UserUtils.class) {
                if (null == instance) {
                    instance = new UserUtils();
                }
            }
        }
        return instance;
    }


    public void init(Context context) {
        this.context = context;
        config = new SharedPrefConfig();
        config.open(context, "user");
        gson = new Gson();
    }


    public void saveAuthor(AuthInfo authInfo) {
        this.authInfo = authInfo;
        config.putString("auth", gson.toJson(authInfo));
    }

    public AuthInfo getAuthor() {
        if (authInfo != null)
            return authInfo;
        if (!TextUtils.isEmpty(config.getString("auth", ""))) {
            return gson.fromJson(config.getString("auth", ""), AuthInfo.class);
        }
        return null;
    }


    public void savePhone(String phone) {
        config.putString("phone", phone);
    }

    public String getPhone() {
        return config.getString("phone", "");
    }

    public void removeAuthor() {
        authInfo = null;
        config.remove("auth");
    }

    public void removeAgent() {
        agent = null;
        config.remove("agent");
    }


    public void saveAgent(Agent agent) {
        this.agent = agent;
        config.putString("agent", gson.toJson(agent));
    }

    public Agent getAgent() {
        if (agent != null)
            return agent;
        if (!TextUtils.isEmpty(config.getString("agent", ""))) {
            return gson.fromJson(config.getString("agent", ""), Agent.class);
        }
        return null;
    }


    public void goToLogin(Activity context){
        removeAuthor();
        removeAgent();
        context.startActivity(new Intent(context, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
        context.finish();
    }


}
